package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ecnu.common.constant.HttpStatus;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysUser;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.exception.ServiceException;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectMessage;
import com.ecnu.system.domain.ProjectUser;
import com.ecnu.system.domain.dto.ProjectUserDTO;
import com.ecnu.system.domain.dto.ProjectUserFalseDTO;
import com.ecnu.system.domain.vo.ProUserVO;
import com.ecnu.system.domain.vo.ProjectByUserVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IEmailService;
import com.ecnu.system.service.IProjectJoinService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 公告 服务层实现
 *
 * @author ruoyi
 */
@Service
public class ProjectJoinServiceImpl implements IProjectJoinService {
    @Autowired
    private ProjectJoinMapper projectJoinMapper;
    @Autowired
    private ProjectMessageMapper projectMessageMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IEmailService emailService;
    @Autowired
    private ProjectUserMapper projectUserMapper;

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setPageNum(new PageInfo(list).getPageNum());
        rspData.setPageSize(new PageInfo(list).getPageSize());
        return rspData;
    }

    @Override
    public int insertProjectUser(ProjectUser user) {
        user.setId(getId());
        LambdaQueryWrapper<ProjectUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectUser::getProId,user.getProId());
        wrapper.eq(ProjectUser::getUserId,user.getUserId());
        wrapper.eq(ProjectUser::getStatus,"1");
        List<ProjectUser> projectUsers = projectUserMapper.selectList(wrapper);
        if (projectUsers!=null&&projectUsers.size()!=0) {
            throw new ServiceException("已提交申请，请勿重复提交",HttpStatus.ACCEPTED);
        }
        if (user.getStatus().equals("0")) {
            user.setTeacherName(user.getUserName());
        }
        if (StringUtils.isNotBlank(user.getTeacherName())) {
            String convertedTeacherName = OtherUtil.convertSpecialCharacters(user.getTeacherName());
            user.setTeacherName(convertedTeacherName);
        }
        int i = projectUserMapper.insert( user);
//        int i = projectJoinMapper.insertProjectUser(user);
        if (i == 0) {
            return 0;
        }
        if (user.getStatus().equals("1")) {
            new Thread(() -> {//审核
                Project one = projectMapper.selectOne(new QueryWrapper<Project>().eq("id", user.getProId()));
                SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(one.getCreateUser()));
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(one.getId());
                projectMessage.setTitle("您好，" + user.getUserName() + " 提交加入活动【" + one.getProName() + "】 的申请，请点击跳转审批");
                projectMessage.setDeptId(String.valueOf(sysUser.getDeptId()));
                projectMessage.setType("1");
                projectMessage.setStatus("0");
                projectMessage.setCreateUser(String.valueOf(user.getUserId()));
                projectMessage.setCreateName(user.getUserName());
//                projectMessage.setUpdateName(loginUser.getUser().getNickName());
//                projectMessage.setUpdateUser(String.valueOf(loginUser.getUserId()));
                projectMessageMapper.insert(projectMessage);
                // 项学生推送报名成功消息
                emailService.ReviewJoinEmail(one,user,sysUser);
            }).start();
        }else {
            new Thread(() -> {//通知
                Project one = projectMapper.selectOne(new QueryWrapper<Project>().eq("id", user.getProId()));
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(one.getId());
                projectMessage.setTitle("您好，您已加入【" + one.getProName() + "】 活动");
//                projectMessage.setDeptId(String.valueOf(user));
                projectMessage.setType("1");
                projectMessage.setStatus("0");
                projectMessage.setCreateUser(String.valueOf(user.getUserId()));
                projectMessage.setCreateName(user.getUserName());
                projectMessageMapper.insert(projectMessage);
            }).start();
        }
        return i;
    }

    @Override
    public List<ProjectUser> selectUnauditUser(String status) {
        return projectJoinMapper.selectUnauditUser(status);
    }

    @Override
    public TableDataInfo selectProUserById(ProjectUserDTO projectUserDTO) {
        startPage(projectUserDTO.getPageDomain());
        List<ProjectUser> projectUserList = projectJoinMapper.selectProUserById(projectUserDTO, projectUserDTO.getProId());
        return getDataTable(projectUserList);
    }

    @Override
    public int updateJoinStatus(ProjectUserFalseDTO dto, LoginUser loginUser) {
        ProjectUser projectUser = projectUserMapper.selectById(dto.getId());
        if (projectUser == null) {
            return 1;
        }
        if (!projectUser.getStatus().equals("1")) {
            throw  new ServiceException("该审批已完成，请勿重复提交",HttpStatus.ACCEPTED);
        }
        if (dto.getStatus().equals("1")){
            dto.setStatus("0");
        }
        int i = projectJoinMapper.updateJoinStatus(dto);
        if (i == 1) {
            new Thread(() -> {//通知
                ProjectByUserVO one = projectMapper.getOne(dto);
                ProjectMessage projectMessage = new ProjectMessage();
                projectMessage.setId(getId());
                projectMessage.setSuperId(dto.getId());
                projectMessage.setTitle("您好，您发起的加入【" + one.getName() + "】 活动的申请，已由 "+loginUser.getUser().getNickName()+" 完成审批");
                projectMessage.setDeptId(String.valueOf(loginUser.getUser().getDeptId()));
                projectMessage.setType("1");
                projectMessage.setStatus("0");
                projectMessage.setCreateUser(String.valueOf(one.getUserId()));
                projectMessage.setCreateName(one.getNickName());
                projectMessage.setUpdateName(loginUser.getUser().getNickName());
                projectMessage.setUpdateUser(String.valueOf(loginUser.getUserId()));
                projectMessageMapper.insert(projectMessage);
                // 推送审核完成邮件
                emailService.ReviewJoinCompletedEmail(one,loginUser,dto.getStatus());
            }).start();
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public AjaxResult selectProUserInfo(String id) {
        QueryWrapper<ProjectUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        ProjectUser user = projectJoinMapper.selectOne(wrapper);
        if (user != null) {
            ProUserVO proUserVO = new ProUserVO();
            BeanUtils.copyProperties(user,proUserVO);
            Project project = projectMapper.selectOne(new QueryWrapper<Project>().eq("id", proUserVO.getProId()));
            proUserVO.setProName(project.getProName());
            if (proUserVO.getStatus().equals("0")){
                proUserVO.setStatusName("通过");
            }else if (proUserVO.getStatus().equals("2")){
                proUserVO.setStatusName("未通过");
            }else {
                proUserVO.setStatusName("待审核");
            }
            return AjaxResult.success(proUserVO);
        }
        return AjaxResult.error("报名信息不存在");
    }

    @Override
    public ProjectUser selectProJoinStatus(String userId, String proId) {
        return projectJoinMapper.selectProJoinStatus(userId, proId);
    }

}
